<?php
define("EW_PAGE_ID", "update", TRUE); // Page ID
define("EW_TABLE_NAME", 'tb_register', TRUE);
?>
<?php 
session_start(); // Initialize session data
ob_start(); // Turn on output buffering
?>
<?php include "ewcfg50.php" ?>
<?php include "ewmysql50.php" ?>
<?php include "phpfn50.php" ?>
<?php include "tb_registerinfo.php" ?>
<?php include "userfn50.php" ?>
<?php include "tb_usersinfo.php" ?>
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
?>
<?php

// Open connection to the database
$conn = ew_Connect();
?>
<?php
$Security = new cAdvancedSecurity();
?>
<?php
if (!$Security->IsLoggedIn()) $Security->AutoLogin();
if (!$Security->IsLoggedIn()) {
	$Security->SaveLastUrl();
	Page_Terminate("login.php");
}
?>
<?php

// Common page loading event (in userfn*.php)
Page_Loading();
?>
<?php

// Page load event, used in current page
Page_Load();
?>
<?php
$tb_register->Export = @$_GET["export"]; // Get export parameter
$sExport = $tb_register->Export; // Get export parameter, used in header
$sExportFile = $tb_register->TableVar; // Get export file, used in header
?>
<?php
$arRecKeys = array();
$nKeySelected = 0;
$sFilter = "";

// Try to load keys from list form
$nKeySelected = 0;
if (ew_IsHttpPost()) {
	if (isset($_POST["key_m"])) { // Key count > 0
		$nKeySelected = count($_POST["key_m"]); // Get number of keys
		$arRecKeys = ew_StripSlashes($_POST["key_m"]);
		LoadMultiUpdateValues(); // Load initial values to form
	}
}

// Try to load key from update form
if ($nKeySelected == 0) {
	$arRecKeys = array();

	// Create form object
	$objForm = new cFormObj();
	if (@$_POST["a_update"] <> "") {

		// Get action
		$tb_register->CurrentAction = $_POST["a_update"];

		// Get record keys
		$sKey = @$_POST["k" . strval($nKeySelected+1) . "_key"];
		while ($sKey <> "") {
			$arRecKeys[$nKeySelected] = ew_StripSlashes($sKey);
			$nKeySelected++;
			$sKey = @$_POST["k" . strval($nKeySelected+1) . "_key"];
		}
		LoadFormValues(); // Get form values
	}
}
if ($nKeySelected <= 0) Page_Terminate("tb_registerlist.php"); // No records selected, return
switch ($tb_register->CurrentAction) {
	case "U": // Update
		if (UpdateRows()) { // Update Records based on key
			$_SESSION[EW_SESSION_MESSAGE] = "Update successful"; // Set update success message
			Page_Terminate("tb_registerlist.php"); // Return to list page
		} else {
			RestoreFormValues(); // Restore form values
		}
}

// Render row
$tb_register->RowType = EW_ROWTYPE_EDIT; // Render edit
RenderRow();
?>
<?php include "header.php" ?>
<script type="text/javascript">
<!--
var EW_PAGE_ID = "update"; // Page id

//-->
</script>
<script type="text/javascript">
<!--

function ew_ValidateForm(fobj) {
	if (fobj.a_confirm && fobj.a_confirm.value == "F")
		return true;
	if (!ew_UpdateSelected()) {
		alert('No field selected for update');
		return false;
	}
	var uelm;
	var i, elm, aelm, infix;
	var rowcnt = (fobj.key_count) ? Number(fobj.key_count.value) : 1;
	for (i=0; i<rowcnt; i++) {
		infix = (fobj.key_count) ? String(i+1) : "";
		elm = fobj.elements["x" + infix + "_RegisterID"];
		uelm = fobj.elements["u" + infix + "_RegisterID"];
		if (uelm && uelm.checked) {
			if (elm && !ew_HasValue(elm)) {
				if (!ew_OnError(elm, "Please enter required field - Register ID"))
				return false;
			}
		}
		elm = fobj.elements["x" + infix + "_LocationID"];
		uelm = fobj.elements["u" + infix + "_LocationID"];
		if (uelm && uelm.checked) {
			if (elm && !ew_HasValue(elm)) {
				if (!ew_OnError(elm, "Please enter required field - Location ID"))
				return false;
			}
		}
	}
	return true;
}

//-->
</script>
<script type="text/javascript">
<!--
var ew_DHTMLEditors = [];

//-->
</script>
<script type="text/javascript">
<!--
var ew_MultiPagePage = "Page"; // multi-page Page Text
var ew_MultiPageOf = "of"; // multi-page Of Text
var ew_MultiPagePrev = "Prev"; // multi-page Prev Text
var ew_MultiPageNext = "Next"; // multi-page Next Text

//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--

// Write your client script here, no need to add script tags.
// To include another .js script, use:
// ew_ClientScriptInclude("my_javascript.js"); 
//-->

</script>
<script language="javascript">
<!--

function ew_SelectAll(bChecked)	{
	var f = document.ftb_registerupdate;
	var sCtrl = "u";
	for (i=0; i<f.elements.length; i++) {
		var elm = f.elements[i];
		if (elm.type == "checkbox" && elm.name.substr(0, sCtrl.length+1) == sCtrl + "_") {
			elm.checked = bChecked;
		}
	}
}

function ew_UpdateSelected() {
	var f = document.ftb_registerupdate;
	var sCtrl = "u";
	for (i=0; i<f.elements.length; i++) {
		var elm = f.elements[i];
		if (elm.type == "checkbox" && elm.name.substr(0, sCtrl.length+1) == sCtrl + "_") {
			if (elm.checked) return true;
		}
	}
	return false;
}

//-->
</script>
<p><span class="phpmaker">Update TABLE: Registers<br><br><a href="tb_registerlist.php">Back to List</a></span></p>
<?php
if (@$_SESSION[EW_SESSION_MESSAGE] <> "") {
?>
<p><span class="ewmsg"><?php echo $_SESSION[EW_SESSION_MESSAGE] ?></span></p>
<?php
	$_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message
}
?>
<form name="ftb_registerupdate" id="ftb_registerupdate" action="tb_registerupdate.php" method="post" onSubmit="return ew_ValidateForm(this);">
<p>
<input type="hidden" name="a_update" id="a_update" value="U">
<?php for ($i = 0; $i < $nKeySelected; $i++) { ?>
<input type="hidden" name="k<?php echo $i+1 ?>_key" id="key<?php echo $i+1 ?>" value="<?php echo ew_HtmlEncode($arRecKeys[$i]) ?>">
<?php } ?>
<table class="ewTable">
	<tr class="ewTableHeader">
		<td>Update<input type="checkbox" value="" onClick="ew_SelectAll(this.checked);"></td>
		<td>Field Name</td>
		<td>New Value</td>
	</tr>
	<tr class="ewTableRow">
		<td<?php echo $tb_register->RegisterID->CellAttributes() ?>>
<input type="checkbox" name="u_RegisterID" id="u_RegisterID" value="1"<?php echo ($tb_register->RegisterID->MultiUpdate == "1")?" checked":"" ?>>
</td>
		<td<?php echo	$tb_register->RegisterID->CellAttributes() ?>>Register ID</td>
		<td<?php echo $tb_register->RegisterID->CellAttributes() ?>><span id="cb_x_RegisterID">
<input type="text" name="x_RegisterID" id="x_RegisterID" title="" size="30" maxlength="6" value="<?php echo $tb_register->RegisterID->EditValue ?>"<?php echo $tb_register->RegisterID->EditAttributes() ?>>
</span></td>
	</tr>
	<tr class="ewTableAltRow">
		<td<?php echo $tb_register->LocationID->CellAttributes() ?>>
<input type="checkbox" name="u_LocationID" id="u_LocationID" value="1"<?php echo ($tb_register->LocationID->MultiUpdate == "1")?" checked":"" ?>>
</td>
		<td<?php echo	$tb_register->LocationID->CellAttributes() ?>>Location ID</td>
		<td<?php echo $tb_register->LocationID->CellAttributes() ?>><span id="cb_x_LocationID">
<select id="x_LocationID" name="x_LocationID"<?php echo $tb_register->LocationID->EditAttributes() ?>>
<!--option value="">Please Select</option-->
<?php
if (is_array($tb_register->LocationID->EditValue)) {
	$arwrk = $tb_register->LocationID->EditValue;
	$rowswrk = count($arwrk);
	for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) {
		$selwrk = (strval($tb_register->LocationID->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected" : "";	
?>
<option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>>
<?php echo $arwrk[$rowcntwrk][1] ?>
</option>
<?php
			}
}
?>
</select>
<?php
$sSqlWrk = "SELECT `ID`, `LocationName` FROM `tb_locations`";
$sSqlWrk .= " ORDER BY `LocationName`";
$sSqlWrk = TEAencrypt($sSqlWrk, EW_RANDOM_KEY);
?>
<input type="hidden" name="s_x_LocationID" id="s_x_LocationID" value="<?php echo $sSqlWrk ?>"><input type="hidden" name="lc_x_LocationID" id="lc_x_LocationID" value="2"><input type="hidden" name="ld1_x_LocationID" id="ld1_x_LocationID" value="1"><input type="hidden" name="ld2_x_LocationID" id="ld2_x_LocationID" value="-1"><input type="hidden" name="lft_x_LocationID" id="lft_x_LocationID" value="1">
</span></td>
	</tr>
	<tr class="ewTableRow">
		<td<?php echo $tb_register->CreateDate->CellAttributes() ?>>
<input type="checkbox" name="u_CreateDate" id="u_CreateDate" value="1"<?php echo ($tb_register->CreateDate->MultiUpdate == "1")?" checked":"" ?>>
</td>
		<td<?php echo	$tb_register->CreateDate->CellAttributes() ?>>Create Date</td>
		<td<?php echo $tb_register->CreateDate->CellAttributes() ?>><span id="cb_x_CreateDate">
<input type="hidden" name="x_CreateDate" id="x_CreateDate" value="<?php echo ew_HtmlEncode($tb_register->CreateDate->CurrentValue) ?>">
</span></td>
	</tr>
</table>
<p>
<input type="submit" name="btnAction" id="btnAction" value="  Update  ">
</form>
<script language="JavaScript">
<!--
var f = document.ftb_registerupdate;
ew_AjaxUpdateOpt(f.x_LocationID, f.x_LocationID, false);

//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--

// Write your table-specific startup script here
// document.write("page loaded");
//-->

</script>
<?php include "footer.php" ?>
<?php

// If control is passed here, simply terminate the page without redirect
Page_Terminate();

// -----------------------------------------------------------------
//  Subroutine Page_Terminate
//  - called when exit page
//  - clean up connection and objects
//  - if url specified, redirect to url, otherwise end response
function Page_Terminate($url = "") {
	global $conn;

	// Page unload event, used in current page
	Page_Unload();

	// Global page unloaded event (in userfn*.php)
	Page_Unloaded();

	 // Close Connection
	$conn->Close();

	// Go to url if specified
	if ($url <> "") {
		ob_end_clean();
		header("Location: $url");
	}
	exit();
}
?>
<?php

// Load initial values to form if field values are identical in all selected records
function LoadMultiUpdateValues() {
	global $arRecKeys, $nKeySelected, $tb_register;

	// Build sql
	$sWrkFilter = "";
	for ($i = 0; $i < $nKeySelected; $i++) {
		$sFilter = $tb_register->SqlKeyFilter();
		$sKey = trim($arRecKeys[$i]);
		$sKeyFld = $sKey;
		if (!is_numeric($sKeyFld)) return;
		$sFilter = str_replace("@ID@", ew_AdjustSql($sKeyFld), $sFilter); // Replace key value
		if ($sWrkFilter <> "") $sWrkFilter .= " OR ";
		$sWrkFilter .= $sFilter;
	}
	$tb_register->CurrentFilter = $sWrkFilter;

	// Load recordset
	$rs = LoadRecordset();
	$i = 1;
	while (!$rs->EOF) {
		if ($i == 1) {
			$tb_register->RegisterID->setDbValue($rs->fields('RegisterID'));
			$tb_register->LocationID->setDbValue($rs->fields('LocationID'));
			$tb_register->CreateDate->setDbValue($rs->fields('CreateDate'));
		} else {
			if (!ew_CompareValue($tb_register->RegisterID->DbValue, $rs->fields('RegisterID'))) {
				$tb_register->RegisterID->CurrentValue = NULL;
			}
			if (!ew_CompareValue($tb_register->LocationID->DbValue, $rs->fields('LocationID'))) {
				$tb_register->LocationID->CurrentValue = NULL;
			}
			if (!ew_CompareValue($tb_register->CreateDate->DbValue, $rs->fields('CreateDate'))) {
				$tb_register->CreateDate->CurrentValue = NULL;
			}
		}
		$i++;
		$rs->MoveNext();
	}
	$rs->Close();
}

// Update all selected rows
function UpdateRows() {
	global $conn, $nKeySelected, $arRecKeys, $tb_register;
	$conn->BeginTrans();

	// Update all rows
	$sKey = "";
	for ($i = 0; $i < $nKeySelected; $i++) {
		$sThisKey = trim($arRecKeys[$i]);
		$sKeyFld = $sThisKey;
		if (!is_numeric($sKeyFld)) {
			return FALSE;
		}
		$tb_register->ID->CurrentValue = $sKeyFld;
		$tb_register->SendEmail = FALSE; // Do not send email on update success
		$UpdateRows = EditRow(); // Update this row
		if (!$UpdateRows) break; // Update failed
		if ($sKey <> "") $sKey .= ", ";
		$sKey .= $sThisKey;
	}

	// Check if all rows updated
	if ($UpdateRows) {
		$conn->CommitTrans(); // Commit transaction
	} else {
		$conn->RollbackTrans(); // Rollback transaction
	}
	return $UpdateRows;
}
?>
<?php

// Load form values
function LoadFormValues() {

	// Load from form
	global $objForm, $tb_register;
	$tb_register->RegisterID->setFormValue($objForm->GetValue("x_RegisterID"));
	$tb_register->RegisterID->MultiUpdate = $objForm->GetValue("u_RegisterID");
	$tb_register->LocationID->setFormValue($objForm->GetValue("x_LocationID"));
	$tb_register->LocationID->MultiUpdate = $objForm->GetValue("u_LocationID");
	$tb_register->CreateDate->setFormValue($objForm->GetValue("x_CreateDate"));
	$tb_register->CreateDate->CurrentValue = ew_UnFormatDateTime($tb_register->CreateDate->CurrentValue, 5);
	$tb_register->CreateDate->MultiUpdate = $objForm->GetValue("u_CreateDate");
}

// Restore form values
function RestoreFormValues() {
	global $tb_register;
	$tb_register->RegisterID->CurrentValue = $tb_register->RegisterID->FormValue;
	$tb_register->LocationID->CurrentValue = $tb_register->LocationID->FormValue;
	$tb_register->CreateDate->CurrentValue = $tb_register->CreateDate->FormValue;
	$tb_register->CreateDate->CurrentValue = ew_UnFormatDateTime($tb_register->CreateDate->CurrentValue, 5);
}
?>
<?php

// Load recordset
function LoadRecordset($offset = -1, $rowcnt = -1) {
	global $conn, $tb_register;

	// Call Recordset Selecting event
	$tb_register->Recordset_Selecting($tb_register->CurrentFilter);

	// Load list page sql
	$sSql = $tb_register->SelectSQL();
	if ($offset > -1 && $rowcnt > -1) $sSql .= " LIMIT $offset, $rowcnt";

	// Load recordset
	$conn->raiseErrorFn = 'ew_ErrorFn';	
	$rs = $conn->Execute($sSql);
	$conn->raiseErrorFn = '';

	// Call Recordset Selected event
	$tb_register->Recordset_Selected($rs);
	return $rs;
}
?>
<?php

// Render row values based on field settings
function RenderRow() {
	global $conn, $Security, $tb_register;

	// Call Row Rendering event
	$tb_register->Row_Rendering();

	// Common render codes for all row types
	// RegisterID

	$tb_register->RegisterID->CellCssStyle = "";
	$tb_register->RegisterID->CellCssClass = "";

	// LocationID
	$tb_register->LocationID->CellCssStyle = "";
	$tb_register->LocationID->CellCssClass = "";

	// CreateDate
	$tb_register->CreateDate->CellCssStyle = "";
	$tb_register->CreateDate->CellCssClass = "";
	if ($tb_register->RowType == EW_ROWTYPE_VIEW) { // View row
	} elseif ($tb_register->RowType == EW_ROWTYPE_ADD) { // Add row
	} elseif ($tb_register->RowType == EW_ROWTYPE_EDIT) { // Edit row

		// RegisterID
		$tb_register->RegisterID->EditCustomAttributes = "";
		$tb_register->RegisterID->EditValue = ew_HtmlEncode($tb_register->RegisterID->CurrentValue);

		// LocationID
		$tb_register->LocationID->EditCustomAttributes = "";
		$sSqlWrk = "SELECT `ID`, `LocationName` FROM `tb_locations`";
		if (trim(strval($tb_register->LocationID->CurrentValue)) == "") {
			$sSqlWrk .= " WHERE 0=1";
		} else {
			$sSqlWrk .= " WHERE `ID` = " . ew_AdjustSql($tb_register->LocationID->CurrentValue) . "";
		}
		$rswrk = $conn->Execute($sSqlWrk);
		$arwrk = ($rswrk) ? $rswrk->GetRows() : array();
		if ($rswrk) $rswrk->Close();
		array_unshift($arwrk, array("", "Please Select"));
		$tb_register->LocationID->EditValue = $arwrk;
	} elseif ($tb_register->RowType == EW_ROWTYPE_SEARCH) { // Search row
	}

	// Call Row Rendered event
	$tb_register->Row_Rendered();
}
?>
<?php

// Update record based on key values
function EditRow() {
	global $conn, $Security, $tb_register;
	$sFilter = $tb_register->SqlKeyFilter();
	if (!is_numeric($tb_register->ID->CurrentValue)) {
		return FALSE;
	}
	$sFilter = str_replace("@ID@", ew_AdjustSql($tb_register->ID->CurrentValue), $sFilter); // Replace key value
	$tb_register->CurrentFilter = $sFilter;
	$sSql = $tb_register->SQL();
	$conn->raiseErrorFn = 'ew_ErrorFn';
	$rs = $conn->Execute($sSql);
	$conn->raiseErrorFn = '';
	if ($rs === FALSE)
		return FALSE;
	if ($rs->EOF) {
		$EditRow = FALSE; // Update Failed
	} else {

		// Save old values
		$rsold =& $rs->fields;
		$rsnew = array();

		// Field RegisterID
		if ($tb_register->RegisterID->MultiUpdate == "1") {
		$tb_register->RegisterID->SetDbValueDef($tb_register->RegisterID->CurrentValue, "");
		$rsnew['RegisterID'] =& $tb_register->RegisterID->DbValue;
		}

		// Field LocationID
		if ($tb_register->LocationID->MultiUpdate == "1") {
		$tb_register->LocationID->SetDbValueDef($tb_register->LocationID->CurrentValue, NULL);
		$rsnew['LocationID'] =& $tb_register->LocationID->DbValue;
		}

		// Field CreateDate
		if ($tb_register->CreateDate->MultiUpdate == "1") {
		$tb_register->CreateDate->SetDbValueDef(ew_CurrentDate(), ew_CurrentDate());
		$rsnew['CreateDate'] =& $tb_register->CreateDate->DbValue;
		}

		// Call Row Updating event
		$bUpdateRow = $tb_register->Row_Updating($rsold, $rsnew);
		if ($bUpdateRow) {
			$conn->raiseErrorFn = 'ew_ErrorFn';
			$EditRow = $conn->Execute($tb_register->UpdateSQL($rsnew));
			$conn->raiseErrorFn = '';
		} else {
			if ($tb_register->CancelMessage <> "") {
				$_SESSION[EW_SESSION_MESSAGE] = $tb_register->CancelMessage;
				$tb_register->CancelMessage = "";
			} else {
				$_SESSION[EW_SESSION_MESSAGE] = "Update cancelled";
			}
			$EditRow = FALSE;
		}
	}

	// Call Row Updated event
	if ($EditRow) {
		$tb_register->Row_Updated($rsold, $rsnew);
	}
	$rs->Close();
	return $EditRow;
}
?>
<?php

// Page Load event
function Page_Load() {

	//echo "Page Load";
}

// Page Unload event
function Page_Unload() {

	//echo "Page Unload";
}
?>
